<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Document</title>
		<script>
			class MyPromise {
				constructor(callback) {
					this.status = 'pending'
					this.fulled = 'fulled'
					this.success = 'reslove'
					this.pending = 'pending'
					this.resloveTask = []
					this.fulledTask = []
					try {
						callback(this.reslove.bind(this), this.reject.bind(this))
					} catch (error) {
						this.reject(error)
					}
				}
				reslove(resloveData) {
					if (this.status === this.pending) {
						this.status = this.success
						this.resloveTask.forEach(cb => {
							cb(resloveData)
						})
					}
				}
				reject(fulledData) {
					if (this.status == this.pending) {
						this.status = this.fulled
						this.fulledTask.forEach(cb => {
							cb(fulledData)
						})
					}
				}
				then(thenCallback, catchCallback) {
					thenCallback && this.resloveTask.push(thenCallback)
					catchCallback && this.fulledTask.push(catchCallback)
					return new Promise((reslove, reject) => {})
				}
				catch(catchCallback) {
					console.log(this)
					this.fulledTask.push(catchCallback)
				}
				then(onFulfilled, onReject) {
					// 保存前一个promise的this
					const self = this
					return new MyPromise((resolve, reject) => {
						// 封装前一个promise成功时执行的函数
						let fulfilled = () => {
							try {
								const result = onFulfilled(self.value) // 承前
								return result instanceof MyPromise ? result.then(resolve, reject) : resolve(result) //启后
							} catch (err) {
								reject(err)
							}
						}
						// 封装前一个promise失败时执行的函数
						let rejected = () => {
							try {
								const result = onReject(self.reason)
								return result instanceof MyPromise ? result.then(resolve, reject) : reject(result)
							} catch (err) {
								reject(err)
							}
						}
						switch (self.status) {
							case PENDING:
								self.onFulfilledCallbacks.push(fulfilled)
								self.onRejectedCallbacks.push(rejected)
								break
							case FULFILLED:
								fulfilled()
								break
							case REJECT:
								rejected()
								break
						}
					})
				}
			}
			new MyPromise((reslove, reject) => {
				setTimeout(() => {
					reject('失败')
					reslove(1000)
				}, 2000)
			})
				.then(
					res => {
						console.log(res, 'success')
					},
					res => {
						console.log(res, 'reject')
					}
				)
				.catch(res => {
					console.log(res, 'catch')
				})
		</script>
	</head>

	<body></body>
</html>
